package org.dragonnova.iot.business.cloud.transport.service;

import io.netty.channel.ChannelHandler.Sharable;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;

import org.dragonnova.iot.business.cloud.conf.Constants;
import org.dragonnova.iot.business.cloud.mq.message.Message;
import org.dragonnova.iot.business.cloud.mq.message.TagAlarmMessage;
import org.dragonnova.iot.business.cloud.mq.message.TagMessage;
import org.dragonnova.iot.business.cloud.statistics.MessageProcessor;
import org.springframework.beans.factory.annotation.Autowired;

@Sharable
public class TagMessageTransport extends ChannelInboundHandlerAdapter {

	// @Autowired
	// private TagMessageMqService mqService;

	@Autowired
	private MessageProcessor messageProcessor;

	/**
	 * @description:
	 * @author songxy DateTime 2017年4月24日 上午10:59:52
	 * @param ctx
	 * @throws Exception
	 */

	@Override
	public void channelActive(ChannelHandlerContext ctx) throws Exception {
		super.channelActive(ctx);
	}

	/**
	 * @description:
	 * @author songxy DateTime 2017年4月24日 上午10:59:52
	 * @param ctx
	 * @param msg
	 * @throws Exception
	 */

	@Override
	public void channelRead(ChannelHandlerContext ctx, Object msg)
			throws Exception {
		if (msg instanceof TagMessage) {
			TagMessage tagMsg = (TagMessage) msg;
			messageProcessor.putUpFlow(1.0 * tagMsg.getPackageCount());
			if (tagMsg.getTemperature() > Constants.MAX_THRESHOLD_TEMPERATURE_VALUE
					|| tagMsg.getTemperature() < Constants.MIN_THRESHOLD_TEMPERATURE_VALUE) {
				Message procMessage = createMessage(tagMsg);
				messageProcessor.putThreshold(procMessage.getId(), procMessage);
			}
		}
	}

	/**
	 * @description:
	 * @author songxy DateTime 2017年4月24日 上午10:59:52
	 * @param ctx
	 * @throws Exception
	 */

	@Override
	public void channelReadComplete(ChannelHandlerContext ctx) throws Exception {
		super.channelReadComplete(ctx);
	}

	/**
	 * @description:
	 * @author songxy DateTime 2017年4月24日 上午10:59:52
	 * @param ctx
	 * @param cause
	 * @throws Exception
	 */

	@Override
	public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause)
			throws Exception {
		super.exceptionCaught(ctx, cause);
	}

	private Message createMessage(TagMessage msg) {
		TagAlarmMessage alarmMessage = new TagAlarmMessage();
		Map<String, String> event = new HashMap<>();
		event.put(
				"battery",
				msg.getBattery() == null ? ""
						: Float.toString(msg.getBattery()));
		event.put(
				"temperature",
				msg.getTemperature() == null ? "8888" : Float.toString(msg
						.getTemperature()));
		alarmMessage.setAlertEvent(event);
		alarmMessage.setId(Constants.idGenerator.generateId().toString());
		alarmMessage.setTagSn(Long.toString(msg.getPhone()));
		alarmMessage.setCreateTime(new Date());
		return alarmMessage;
	}
}
